using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Runtime.Serialization;
using System.Xml.Serialization;
using CMUSHrun.Objects;

namespace CMUSHrun.Database
{
    public class MushDatabase
    {
        /// <summary>
        /// The mush database
        /// </summary>
        private List<MushObject> _database = new List<MushObject>();

        /// <summary>
        /// Returns the 
        /// </summary>
        /// <param name="ID"></param>
        /// <returns></returns>
        public MushObject GetByID(int ID)
        {
            return _database[ID];
        }

        /// <summary>
        /// Create a new player object in the database
        /// </summary>
        /// <returns>the new player object</returns>
        public MushPlayer NewPlayer()
        {
            // Make a new object
            MushPlayer mp = new MushPlayer();
            mp.DbRef = _database.Count;
            _database.Add(mp);
            return mp;
        }

        /// <summary>
        /// Create a new object object in the database
        /// </summary>
        /// <returns>the new player object</returns>
        public MushObject NewObject()
        {
            // Make a new object
            MushObject mo = new MushObject();
            mo.DbRef = _database.Count;
            mo.Name = "Object #" + mo.DbRef.ToString();
            _database.Add(mo);
            return mo;
        }

        /// <summary>
        /// Serializes the database
        /// </summary>
        /// <param name="filename"></param>
        public void DumpDatabase(String filename)
        {
            //// Insert code to set properties and fields of the object.
            //Type[] extraTypes = new Type[2];
            //extraTypes[0] = typeof(MushObject);
            //extraTypes[1] = typeof(MushPlayer);

            //XmlSerializer mySerializer = new XmlSerializer(typeof(List<MushObject>), extraTypes);
            //// To write to a file, create a StreamWriter object.
            //StreamWriter myWriter = new StreamWriter(filename);
            //mySerializer.Serialize(myWriter, _database);
            //myWriter.Close();

            Serializer.SerializeToDisk(filename, _database[0], Serializer.SerializationFormat.Xml);
        }

        public void LoadDatabase(String filename)
        {
            //// Insert code to set properties and fields of the object.
            //Type[] extraTypes = new Type[2];
            //extraTypes[0] = typeof(MushObject);
            //extraTypes[1] = typeof(MushPlayer);

            //XmlSerializer deserializer = new XmlSerializer(typeof(List<MushObject>), extraTypes);
            //TextReader textReader = new StreamReader(filename);
            //_database = (List<MushObject>)deserializer.Deserialize(textReader);
            //textReader.Close();
        }

    }
}
